import { Button, Col, Row, Card, Avatar, message, List, Drawer } from 'antd'
import axios from 'axios';
import React, { useEffect, useRef, useState } from 'react';
import { EditOutlined, EllipsisOutlined, PieChartOutlined, BarChartOutlined, HeartOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import _ from 'lodash';
import { NavLink } from '_react-router-dom@6.3.0@react-router-dom';
import * as Echarts from 'echarts';
import  homeStyle from  '../css/home.less'
const { Meta } = Card;
// 发起网络请求，home主页页面，要显示发布状态（publishState===2）为 已发布 所有新闻信息,
const getTableDataSourceRequest = () => {
    return Promise.all([
        axios.get(`http://localhost:3000/news?_expand=category&publishState=2&_sort=view&_order=desc&_limit=6`),
        axios.get(`http://localhost:3000/news?_expand=category&publishState=2&_sort=star&_order=desc&_limit=6`),
        axios.get(`http://localhost:3000/news?_expand=category&publishState=2`),
    ])
};

export default function Home() {
    let renderCharts: any;
    // 从本地存储中获取当前用户信息
    const currentUserData: Array<any> = JSON.parse(localStorage.getItem('token') as string);
    // 柱状图的ref，存储dom
    const barRef = useRef<any>();
    const pieRef = useRef<any>();
    // 所有已发布的新闻数据
    const [publishedDataSource, setPublishedDataSource] = useState<any>([]);
    // 所有当前用户已发布的新闻数据
    const [currentPublishedData, setCurrentPublishedData] = useState<any>([]);
    // 浏览最多数据信息
    const [mostViewDataSource, setMostViewDataSource] = useState<any>([]);
    // 浏览器宽度，默认为0
    const [windowWidth, setWindowWidth] = useState<any>(0);
    // 点赞最多的数据信息
    const [mostStarDataSource, setMostStarDataSource] = useState<any>([]);
    const { run: getTableDataSource, loading: getTableDataSourceLoading } = useRequest(getTableDataSourceRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            result.forEach((element: any, index: number) => {
                if (element.status === 200) {
                    switch (index) {
                        case 0:
                            setMostViewDataSource(element.data)
                            break;
                        case 1:
                            setMostStarDataSource(element.data)
                            break;
                        case 2:
                            // console.log(_.groupBy(element.data,item=>item.category.title))
                            setPublishedDataSource(_.groupBy(element.data, item => item.category.title));
                            setCurrentPublishedData(_.groupBy(element.data.filter((item:any)=> item.author===currentUserData[0].username), item => item.category.title))
                            renderBar(_.groupBy(element.data, item => item.category.title))
                            break;
                        default:
                            break;
                    }
                }
            });
        },
        onError(e, params) {
            console.log(e);
            message.warning('请求的新闻数据失败');
        },
    });
    //  通过事件对象获取浏览器窗口大小
    const resizeUpdateWidth = (e: any) => {
        //通过事件对象获取浏览器窗口大小
        let width = e.target.innerWidth;
        setWindowWidth(width);
        renderBar(publishedDataSource);
    };
    // Drawer抽屉组件的显示，默认不显示
    const [open, setOpen] = useState(false);
    // 打开抽屉，让open=>true
    const showDrawer = async() => {
        await setOpen(true);
    };
    // 隐藏抽屉，让open=>false
    const onClose = () => {
        setOpen(false);
    };
    useEffect(() => {
        getTableDataSource();
    }, []);

    useEffect(() => {
        //刚加载是获取浏览器宽度
        let width = window.innerWidth;
        setWindowWidth(width);
        // console.log("width",width);
        // 增加window监听事件，页面变化时获取浏览器窗口的大小
        window.addEventListener('resize', resizeUpdateWidth);
        return () => {
            // 组件销毁时，清除监听事件
            window.removeEventListener('resize', resizeUpdateWidth);
            window.removeEventListener('resize', renderCharts);

        }
    }, [windowWidth]);


    const renderBar = (obj: { [propsName: string]: any }) => {
        // 先判断是否已经存在实例，没有则创建，有则再原实例上进行修改
        let myChart = Echarts.getInstanceByDom(barRef.current as HTMLElement);
        // 判断实例是否存在，如果不存在，则创建新的实例
        if (!myChart) {
            myChart = Echarts.init(barRef.current as HTMLElement);
        }
        // echart 柱状图响应式布局
        renderCharts = () => {
            myChart?.resize();
        };
        //清空监听事件
        window.removeEventListener('resize', renderCharts);
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(obj),
                axisLabel: {
                    // 刻度标签旋转的角度，在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠。
                    rotate: windowWidth > 700 ? 0 : 45,
                    interval: 0
                }
            },
            yAxis: {
                // y坐标轴最小间隔大小
                minInterval: 1
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(obj).map((item: any) => { return item.length })
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        //添加监听事件
        window.addEventListener('resize', renderCharts)
    }

    const renderPieView = () => {
        console.log(currentPublishedData);
        const seriesData=[];
        for(let i in currentPublishedData){
            seriesData.push({
                name:i,
                value:currentPublishedData[i].length
            })
        }
        // console.log(seriesData);
        // 先判断是否已经存在实例，没有则创建，有则再原实例上进行修改
        let myChart = Echarts.getInstanceByDom(pieRef.current as HTMLElement);
        // 判断实例是否存在，如果不存在，则创建新的实例
        if (!myChart) {
            myChart = Echarts.init(pieRef.current as HTMLElement);
        }
        // echart 柱状图响应式布局
        renderCharts = () => {
            myChart?.resize();
        };
        var option;

        option = {
            title:{
                text:`【${currentUserData[0].username}】已发布新闻信息`,
                left:'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [
                {
                    name: 'Access From',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 40,
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: seriesData
                }
            ]
        };

        option && myChart.setOption(option);
    }
    return (
        <div>
            <Row gutter={16}>
                <Col span={8}>
                    <Card className={homeStyle.myCol} title={<><b style={{ 'marginRight': '10px' }}>用户最常浏览</b><BarChartOutlined key="BarChartOutlined" /></>} bordered={true}>
                        <List
                            size="small"
                            dataSource={mostViewDataSource}
                            renderItem={(item: any) => <List.Item>{
                                <NavLink to={`/news-manage/preview/${item.id}`}>{item.title}
                                </NavLink>
                            }</List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card className={homeStyle.myCol} title={<><b style={{ 'marginRight': '10px' }}>用户点赞最多</b><HeartOutlined key="BarChartOutlined" /></>} bordered={true}>
                        <List
                            size="small"
                            dataSource={mostStarDataSource}
                            renderItem={(item: any) => <List.Item>{
                                <NavLink to={`/news-manage/preview/${item.id}`}>{item.title}
                                </NavLink>
                            }</List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card className={homeStyle.myCol}
                        cover={
                            <img
                                alt="example"
                                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                            />
                        }
                        actions={[
                            <PieChartOutlined key="setting" onClick={async () => { 
                                await showDrawer(); 
                                await renderPieView();
                            }} />,
                            <EditOutlined key="edit" />,
                            <EllipsisOutlined key="ellipsis" />,
                        ]}
                    >
                        <Meta
                            avatar={<Avatar src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202102%2F19%2F20210219223710_b5d3b.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674564364&t=f94bd0a0c6ba2eb12196fc2055776934" />}
                            title={currentUserData[0].username}
                            description={<>
                                <span style={{ 'marginRight': '20px', 'fontWeight': 'bold' }}>{currentUserData[0].region ? currentUserData[0].region : '全球'}</span>
                                <span>{currentUserData[0].role.roleName}</span>
                            </>}
                        />
                    </Card>
                </Col>
            </Row>

            <div ref={barRef} style={{ width: '100%', height: '600px', marginTop: '40px' }}></div>
            <Drawer title="个人新闻分类" placement="right" onClose={onClose} open={open} width='500px'>
                <div ref={pieRef} style={{ width: '100%', height: '600px' }}></div>
            </Drawer>
        </div>
    )
}
